package com.zlsy.thread.objectandthreadcommonsuse.parity;

/**
 * @author zhouliang
 * @date 2020/03/06
 * @desc 两个线程交替打印0~100的奇偶数，要求：偶线程打印0，奇线程打印1，如此循环往复 ：synchronized实现
 **/
public class ParityPrintingBySynchronized {


    /**
     * 这种方式不太推荐；
     * 因为假设偶数线程一直获取到锁，那么就会一直执行if的判断，然后又去竞争锁，循环往复。
     */

    private static int count;
    private static final Object instance = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (instance) {
                        if ((count & 1) == 0) {
                            System.out.println(Thread.currentThread().getName() + "，打印：" + count);
                            count++;
                        }
                    }
                }
            }
        }, "偶数").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (instance) {
                        if ((count & 1) == 1) {
                            System.out.println(Thread.currentThread().getName() + "，打印：" + count);
                            count++;
                        }
                    }
                }
            }
        }, "奇数").start();
    }
}
